package rpc

import (
	"RedWork/model"
	"RedWork/rpc/userCenter/userCenter"
	"RedWork/service/etcdv2/efind"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

// userLoginAndRegister
type userLR struct {
	userName string
	passWord string
	node     string
	conn     *grpc.ClientConn
}

func NewUserLrCtl(endpoint, serverName string) (u *userLR) {
	//w := etcd.NewWatcher(endpoint, projectName)
	//node, err2 := w.MatchChildNode(chileNode)
	//if err2 != nil {
	//	log.Println(err2)
	//	return
	//}
	kv, err := efind.NewClient(efind.Config{EtcdAddr: endpoint}).MatchAServer(serverName)
	fmt.Println("使用节点", kv)
	if err != nil {
		log.Println(err)
		return &userLR{}
	}

	conn, err := grpc.Dial(kv.Val, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	userLrCtl := userLR{
		node: kv.Val,
		conn: conn,
	}
	return &userLrCtl
}

// CallRegister 对外调用remote register
func (u *userLR) CallRegister(info model.UserInfo) *userCenter.RegisterRes {
	u.userName = info.UserName
	u.passWord = info.PassWord
	client := userCenter.NewRegisterCenterClient(u.conn)
	return u.register(client)
}

// CallLogin 对外调用remote login
func (u *userLR) CallLogin(info model.UserInfo) *userCenter.LoginRes {
	u.userName = info.UserName
	u.passWord = info.PassWord
	client := userCenter.NewRegisterCenterClient(u.conn)
	return u.login(client)
}

// register
func (user *userLR) register(client userCenter.RegisterCenterClient) *userCenter.RegisterRes {
	res, err := client.Register(context.Background(), &userCenter.RegisterReq{
		UserName: user.userName,
		PassWord: user.passWord,
	})
	if err != nil {
		log.Println(err)
		return &userCenter.RegisterRes{}
	}
	if res.Status == true {
		fmt.Println("SUCCESS")
		return res
	}
	return &userCenter.RegisterRes{}
}

// login
func (user *userLR) login(client userCenter.RegisterCenterClient) *userCenter.LoginRes {
	res, err := client.Login(context.Background(), &userCenter.LoginReq{
		UserName: user.userName,
		PassWord: user.passWord,
	})
	if err != nil {
		log.Println(err)
		return &userCenter.LoginRes{
			Status: false,
			Token:  "",
		}
	}
	return res
}
